package com.wangsd.common.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangsd.common.controller.page.PageDomain;
import com.wangsd.common.controller.page.TableDataInfo;
import com.wangsd.common.controller.page.TableSupport;
import com.wangsd.common.utils.StringUtils;
import com.wangsd.common.utils.sql.SqlUtil;
import com.wangsd.common.utils.text.StrFormatter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author wangsd
 */
public class BaseController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
//    @InitBinder
//    public void initBinder(WebDataBinder binder) {
//        // Date 类型转换
//        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
//            @Override
//            public void setAsText(String text) {
//                setValue(DateUtils.parseDate(text));
//            }
//        });
//    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setList(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    protected PageInfo getPageInfo(Page page, List list) {
        PageInfo pageInfo = new PageInfo(page);
        pageInfo.setList(list);
        return pageInfo;
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StrFormatter.format("redirect:{}", url);
    }

}
